using MalwarePatch.CliTools;
using MalwarePatch.Languages;
using MalwarePatch.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shell;

namespace MalwarePatch
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            AppDomain.CurrentDomain.AssemblyResolve += assemblyResolveHandler;
            //StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute);
            base.OnStartup(e);
            // CultureInfo.CurrentUICulture = new CultureInfo("en-US");
            AppJumpList.CreateJumpList();
#if DEBUG
            File.AppendAllText($"args.txt", string.Join(" ", e.Args));
#endif
            if (SilentUpdater.TryParse(e.Args) ||
                UserCertificateCli.TryParse(e.Args) ||
                MalwareChecker.TryParse(e.Args))
            {
                Shutdown();
            }
            else
            {
                Updater.InstallUpdateAndRun(this, e.Args);
            }
        }
        static Assembly assemblyResolveHandler(object s, ResolveEventArgs e)
        {
            var dllName = new AssemblyName(e.Name).Name + ".dll";
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = assembly.GetManifestResourceNames().FirstOrDefault(name => name.EndsWith(dllName));
            if (resourceName == null)
            {
                return null;
            }
            using (var stream = assembly.GetManifestResourceStream(resourceName))
            {
                var assemblyData = new byte[stream.Length];
                stream.Read(assemblyData, 0, assemblyData.Length);
                return Assembly.Load(assemblyData);
            }
        }
    }
}
